<template>
  <div class="pagination-container" :class="{'hidden':hidden}">
    <el-pagination
      :background="background"
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :layout="layout"
      :page-sizes="pageSizes"
      :total="total"
      v-bind="$attrs"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
import { scrollTo } from '@/utils/scroll-to'
export default {
  name: 'Pagination',
  props: {
    background: {
      type: Boolean,
      default: false
    },
    total: {
      type: Number,
      required: true
    },
    offset: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 10
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 20, 30, 50]
      }
    },
    layout: {
      type: String,
      default: 'sizes,prev,pager,next,jumper' // total
    },
    autoScroll: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    currentPage: {
      get() {
        return 1 + (this.offset / this.limit)
      },
      set(val) {
        this.$emit('update:offset', (val - 1) * this.limit) // 通知父组件 更新 offset
      }
    },
    pageSize: {
      get() {
        return this.limit
      },
      set(val) {
        this.$emit('update:limit', val) // 通知父组件 更新 limit
      }
    }
  },
  methods: {
    handleCurrentChange(val) {
      console.log('当前页:', this.currentPage)
      this.$emit('pagination', { offset: (val - 1) * this.pageSize, limit: this.pageSize })
      if (this.autoScroll) {
        scrollTo(0, 800) // 翻页后 滚动条回到0
      }
    },
    handleSizeChange(val) {
      this.$emit('sizeChange', { offset: (this.currentPage - 1) * this.pageSize, limit: val })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
    }
  }
}
</script>

<style lang="stylus">
.pagination-container {
  text-align: right;
  padding: 10px 0;
}
.pagination-container.hidden {
  display: none;
}
</style>
